package com.browsesoft.user;

import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.EntityManager;
import com.browsesoft.ManagerGroup;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLTreeModel;
import com.browsesoft.resource.BasicResource;
import com.browsesoft.resource.Resource;

public class OrganizationTreeModel implements HTMLTreeModel {
	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
	}

	/**
	 * 根据结点返回子结点
	 * 
	 * @return
	 */
	public LinkedList getChildNodes(Object node) throws Exception {
		BasicResource res = (BasicResource) node;
		// 得到所有用户
		LinkedList result = res.getChildrenByType("user");
		// 得到所有用户组
		result.addAll(res.getChildrenByType("role"));
		// 得到所有组织单元
		result.addAll(res.getChildrenByType("organization"));
		return result;
	}

	/**
	 * 根据结点返回结点的名称
	 * 
	 * @return
	 */
	public String getName(Object node) throws Exception {
		return ((Resource) node).getAttributes().get("name").toString();
	}

	/**
	 * 根据id找到结点对象
	 * 
	 * @return
	 */
	public Object getObject(String ID) throws Exception {
		EntityManager manager = (EntityManager) ManagerGroup.getManagerGroup()
				.getManager("entity");
		return manager.getObject(ID);
	}

	/**
	 * 根据结点返回结点的id
	 * 
	 * @return 结点的名称
	 */
	public String getID(Object node) {
		return ((Resource) node).getID();
	}

	/**
	 * 取得该节点的连接
	 */
	public String getLink(Object node) {
		return "window.open('page.jsp?"
				+ "templatename=userManagerTable.html&point="
				+ this.getID(node) + "', 'right')";
	}

	/**
	 * 取得根结点
	 * 
	 * @return 根结点
	 */
	public Object getRootNode() throws Exception {
		EntityManager manager = (EntityManager) ManagerGroup.getManagerGroup()
				.getManager("entity");
		return manager.getRoot();
	}

	/**
	 * 设置传递的参数
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response) {
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 设置链接内容
	 * 
	 * @param nodeLink
	 *            链接
	 */
	public void setContextNode(Element nodeLink, Object modelNode)
			throws Exception {
	}

	/**
	 * 判断是否有子
	 */
	public boolean hasChilds(Object obj) {
		Resource res = (Resource) obj;
		return res.getChildren().hasNext();
	}

	/**
	 * 得到节点对应的图标
	 * 
	 * @param node
	 *            节点
	 * @return 图标
	 */
	public String getIcon(Object node) {
		String icon = (String) ((Resource) node).getAttributes().get("f_icon");
		if (icon == null) {
			icon = "tree_org";
		}
		return icon;
	}
}